// pages/commentPub/commentPub.js
const api = require('../../utils/backendAPI.js');

Page({
  data: {
    commentFocus: false,
    comment: {
      experiment: 1011,
      comment: '',
      hdwt: 3,
      myd: 3,
      jjxxd: 3,
      df: '',
      teachername: ''
    },
    index: 1011,
    editmode: false,
  },
  onLoad: function (options) {
    if (options.editmode) {
      this.setData({ editmode: options.editmode })
      this.setMyCommentData(options.index)
    }
    this.data.index = options.index
    this.data.comment.experiment = Number(options.index)
  },
  setMyCommentData: function (index) {
    wx.showLoading({
      title: '正在载入数据',
    })
    api.getCommentList({
      experiment: index
    }).then(res => {
      if (res.data.mycomment) {
        Object.assign(res.data.mycomment.comment, { oid: res.data.mycommentid })
        this.setData({ comment: res.data.mycomment.comment })
      }
      else {
        wx.navigateBack()
        wx.showToast({
          title: '没有编辑数据',
          icon: 'none'
        })
      }
      wx.hideLoading()
    }).catch(() => {
      wx.hideLoading()
      wx.navigateBack()
      wx.showToast({
        title: '未能载入数据',
        icon: 'none'
      })
    })
  },
  focusComment: function () {
    this.setData({ commentFocus: true })
  },
  inputHandler: function (e) {
    this.data.comment[e.currentTarget.dataset.item] = e.detail.value
  },
  submitComment: function () {
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    let showToast = (msg, showIcon) => {
      wx.hideLoading({
        success: () => {
          wx.showToast({
            title: msg,
            icon: showIcon ? 'success' : 'none'
          })
        },
      })
    }

    if (this.data.editmode) {
      api.updateComment(this.data.comment).then((res) => {
        if (res.data.code === 0) {
          wx.navigateBack()
          showToast('成功提交', true)
        } else if (res.data.code === 1) {
          showToast('未通过评论审核')
        } else {
          showToast('请求时发生错误')
        }
      }).catch(res => {
        console.warn(res);
        showToast(res.errMsg)
      })
    } else {
      api.uploadComment(this.data.comment).then((res) => {
        if (res.data.code === 0) {
          wx.navigateBack()
          showToast('成功提交', true)
        } else if (res.data.code === 1) {
          showToast('未通过评论审核')
        } else if (res.data.code === 2) {
          showToast('不能重复发表评论')
        } else {
          showToast('请求时发生错误')
        }
      }).catch(res => {
        console.warn(res);
        showToast(res.errMsg)
      })
    }
  }
})